﻿using AutoMapper;
using HamcoWcs.Contract;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.Contract.ContractSrm;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.TibcoMessage.Items;
using HamcoWcs.Models.WcsLocations;
using System.Linq;

namespace HamcoWcs.Service.Common
{
    [AutoInject(typeof(IPalletService), InjectType.Scope)]
    public class PalletService : ScopeServiceBase, IPalletService
    {

        private readonly IMapper _mapper;
        private readonly WcsDbContext _wcsDbContext;
        private readonly AutomaticStorageInfo _asrs;
        private readonly ILocationService _locationService;
        private readonly IBaseSrmTaskService _baseSrmTaskService;
        private readonly IPconBaseService _pconBaseService;

        public PalletService(IMapper mapper, WcsDbContext wcsDbContext, ILocationService locationService, IBaseSrmTaskService baseSrmTaskService, IPconBaseService pconBaseService, AutomaticStorageInfo asrs) : base(wcsDbContext, mapper)
        {
            _locationService = locationService;
            _baseSrmTaskService = baseSrmTaskService;
            _pconBaseService = pconBaseService;
            _asrs = asrs;
        }


        public MachineAddressDto GetPalletAddress(string unitId)
        {
            MachineAddressDto address = null;

            var loc = _locationService.GetPalletLocation(unitId);
            if (loc != null)
            {
                var locDto = _mapper.Map<WcsLocationDto>(loc);
                address = new MachineAddressDto(locDto);
                return address;
            }


            //var srms = _baseSrmTaskService.GetAllSrmPlcs();

            var srms = _asrs.Srms;
            var srm = srms.FirstOrDefault(x => x.UnitId == unitId);
            if (srm != null)
            {
                address = new MachineAddressDto(srm);
                return address;
            }

            var plcs = _pconBaseService.GetAllPconPlcs();
            foreach (var plc in plcs)
            {
                var pcons = plc.Pcons.Values;
                var pcon = pcons.FirstOrDefault(x => x.UnitId == unitId);

                if (pcon != null)
                {
                    address = new MachineAddressDto(pcon);
                    return address;
                }
            }

            return address;
        }
    }
}
